import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    Image,
    ListView, RefreshControl, TouchableOpacity, ActivityIndicator, DeviceEventEmitter
} from 'react-native';
import NavigationBar from '../common/NavigationBar'
import DataRepository,{FLAG_STORAGE} from '../expand/dao/DataRepository'
import ScrollableTabView,{DefaultTabBar, ScrollableTabBar} from 'react-native-scrollable-tab-view'
import {DURATION} from "react-native-easy-toast";
import TrendingCell from "../common/TrendingCell";
import RepositoryDetail from "./RepositoryDetail";
import LanguageDao, {FLAG_LANGUAGE} from '../expand/dao/LanguageDao'
import TimeSpan from '../model/TimeSpan'
import Popover from '../common/Popover'

const API_URL = 'https://github.com/trending/'
const timeSpanArray = [new TimeSpan('今天', 'since=daily'),new TimeSpan('今天', 'since=weekly'),new TimeSpan('今天', 'since=monthly')]

export default class TrendingPage extends Component {
    constructor(props) {
        super(props)
        this.languageDao = new LanguageDao(FLAG_LANGUAGE.flag_language)
        this.dataRepository = new DataRepository()
        this.state={
            result: null,
            dataArray: []
        }
    }
    componentDidMount() {
        this.loadData()
    }
    loadData() {
        this.languageDao.fetch()
            .then((result) => {
                this.setState({
                    dataArray: result
                })
            }).catch((error) => {
            console.log(error)
        })
    }
    renderTitle() {
        return <TouchableOpacity>
            <View style={{flexDirection: 'row', alignItems: 'center'}}>
                <Text>趋势</Text>
                <Image style={{width: 12, height: 12, marginLeft: 5}} source={require('../../res/images/ic_spinner_triangle.png')} />
            </View>
        </TouchableOpacity>
    }
    render() {
        let content = this.state.dataArray.length > 0 ?
            <ScrollableTabView
                tabBarBackgroundColor='#2196F3'
                tabBarInactiveTextColor='mintcream'
                tabBarActiveTextColor='white'
                tabBarUnderlineStyle={{backgroundColor: '#e7e7e7', height: 2}}
                renderTabBar={() => <ScrollableTabBar />}
            >
                {this.state.dataArray.map((item, i, arr) => {
                    let lan = arr[i];
                    return lan.checked ?  <TrendingTab key={i} tabLabel={lan.name} {...this.props}/>:null
                })}
            </ScrollableTabView> : null
        return (
            <View style={styles.container}>
                <NavigationBar
                    title={this.renderTitleView()}
                    statusBar={{backgroundColor: '#2196f3'}}
                />
                {content}
            </View>
        )
    }
}

class TrendingTab extends Component {
    constructor(props) {
        super(props)
        this.dataRepository = new DataRepository(FLAG_STORAGE.flag_trending)
        this.state={
            dataSource: null,
            isLoading: false,
        }
    }
    componentWillMount() {
       this.onLoad()
    }
    onSelect(item) {
        this.props.navigator.push({
            component: RepositoryDetail,
            params: {
                item: item,
                ...this.props
            }
        })
    }
    renderRow(data) {
        return <TrendingCell
            onSelect={data=>this.onSelect(data)}
            key={data.id}
            data={data}/>
    }
    renderSeparator(sectionID, rowID, adjacentRowHighlighted) {
        return <View key={rowID} style={styles.line}></View>
    }
    renderFooter() {
        return <Image style={{width: 100, height: 100}} source={{uri: 'https://segmentfault.com/u/junezm'}}></Image>
    }
    onLoad() {
        this.setState({
            isLoading: true
        })
        //let url = API_URL+this.props.category+timeSpan.searchText
        let url = API_URL+ this.props.tabLabel
        this.dataRepository.fetchRepository(url)
            .then(res => {
                let items = res && res.items ? res.items: res? res: []

                this.setState({
                    isLoading: false,
                    dataSource: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}).cloneWithRows(items)
                })

                if(res&&res.update_date&&!this.dataRepository.checkDate(res.update_date)) {
                    DeviceEventEmitter.emit('showToast', '数据过时')
                    return this.dataRepository.fetchNetRepository(url)
                } else {
                    DeviceEventEmitter.emit('showToast', '显示缓存数据')
                }
            })
            .then(items => {
                if(!items || items.length === 0) return;
                this.setState({
                    isLoading: false,
                    dataSource: new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}).cloneWithRows(items)
                })
                DeviceEventEmitter.emit('showToast', '显示网络数据')
            })
            .catch(error => {
                this.setState({
                    isLoading: false,
                    result: JSON.stringify(error)
                })
            })
    }
    render() {
        if (!this.state.dataSource) { // myList为空的时候显示加载组件，有数据则展示数据
            return (
            <View>
            <ActivityIndicator
            animating={this.state.animating}
            style={[styles.centering, {height: 80}]}
            size="large"
            />
            </View>
            );
        } else {
            return (
            <View style={styles.container}>
                <ListView
                    dataSource={this.state.dataSource}
                    renderRow={(rowData) => this.renderRow(rowData)}
                    refreshControl={<RefreshControl
                        color={['#2196f3']}
                        tintColor={'#2193f3'}
                        title={'加载中...'}
                        titleColor={'#2193f3'}
                        refreshing={this.state.isLoading}
                        onRefresh={()=>this.onLoad()}
                    />
                    }
                />
            </View>
            )
        }
    }
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'white'
    },
    text: {
        fontSize: 20
    },
    row: {
        height: 50
    },
    line: {
        height: 1,
        backgroundColor: 'black'
    },
    centering: {
        alignItems: 'center',
        justifyContent: 'center',
        padding: 8,
    },
});